<template>
  <view class="patient-add-page">
    <view class="page-header">
      <text class="page-title">新增患者档案</text>
      <view class="header-actions">
        <button class="btn btn-default" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">保存</button>
      </view>
    </view>

    <view class="form-content">
      <view class="form-card">
        <view class="card-header">
          <text class="card-title">基本信息</text>
        </view>
        <view class="card-body">
          <view class="form-item required">
            <text class="label">关联用户</text>
            <picker mode="selector" :range="patientUserList" :range-key="'displayName'" :value="selectedUserIndex" @change="handleUserChange">
              <view class="picker-input">{{ selectedUserDisplay || '请选择患者用户' }}</view>
            </picker>
          </view>
          
          <view class="form-item required">
            <text class="label">性别</text>
            <view class="readonly-field">{{ genderOptions[genderIndex]?.label || '未设置' }}</view>
          </view>
          
          <view class="form-item required">
            <text class="label">出生日期</text>
            <view class="readonly-field">{{ birthDateStr || '未设置' }}</view>
          </view>
          
          <view class="form-item">
            <text class="label">身份证号</text>
            <view class="readonly-field">{{ formData.id_card || '未设置' }}</view>
          </view>
          
          <view class="form-item">
            <text class="label">患者联系电话</text>
            <view class="phone-with-badge">
              <view class="readonly-field">{{ formData.mobile || '未设置' }}</view>
              <view v-if="formData.mobile" :class="['verify-badge', formData.mobile_confirmed === 1 ? 'verified' : 'unverified']">
                {{ formData.mobile_confirmed === 1 ? '已认证' : '未认证' }}
              </view>
            </view>
          </view>
          
          <view class="form-item">
            <text class="label">血型</text>
            <picker mode="selector" :range="bloodTypeOptions" :value="bloodTypeIndex" @change="handleBloodTypeChange">
              <view class="picker-input">{{ bloodTypeOptions[bloodTypeIndex] || '请选择' }}</view>
            </picker>
          </view>
        </view>
      </view>

      <view class="form-card">
        <view class="card-header">
          <text class="card-title">医疗信息</text>
        </view>
        <view class="card-body">
          <view class="form-item">
            <text class="label">过敏史</text>
            <input 
              v-model="allergiesStr" 
              class="input" 
              placeholder="多个过敏源用逗号分隔，例如：青霉素、海鲜" 
              @focus="handleInputFocus"
              @blur="handleInputBlur"
            />
          </view>
          
          <view class="form-item">
            <text class="label">慢性病史</text>
            <input 
              v-model="chronicDiseasesStr" 
              class="input" 
              placeholder="多个病史用逗号分隔，例如：高血压、糖尿病" 
              @focus="handleInputFocus"
              @blur="handleInputBlur"
            />
          </view>
        </view>
      </view>

      <view class="form-card">
        <view class="card-header">
          <text class="card-title">紧急联系人</text>
        </view>
        <view class="card-body">
          <view class="form-item">
            <text class="label">联系人姓名</text>
            <input 
              v-model="formData.emergency_contact" 
              class="input" 
              placeholder="请输入联系人姓名" 
              @focus="handleInputFocus"
              @blur="handleInputBlur"
            />
          </view>
          
          <view class="form-item">
            <text class="label">联系人电话</text>
            <input 
              v-model="formData.emergency_phone" 
              class="input" 
              type="number" 
              placeholder="请输入联系电话" 
              @focus="handleInputFocus"
              @blur="handleInputBlur"
            />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

const genderOptions = [
  { label: '未知', value: 0 },
  { label: '男', value: 1 },
  { label: '女', value: 2 }
]
const bloodTypeOptions = ['', 'A型', 'B型', 'AB型', 'O型', 'RH阴性A型', 'RH阴性B型', 'RH阴性AB型', 'RH阴性O型']

const formData = reactive({
  user_id: '',
  gender: 0,
  birth_date: null,
  id_card: '',
  mobile: '',
  mobile_confirmed: 0,
  blood_type: '',
  allergies: [],
  chronic_diseases: [],
  emergency_contact: '',
  emergency_phone: ''
})

const genderIndex = ref(0)
const bloodTypeIndex = ref(0)
const birthDateStr = ref('')
const allergiesStr = ref('')
const chronicDiseasesStr = ref('')

// 患者用户列表相关
const patientUserList = ref([])
const selectedUserIndex = ref(-1)
const selectedUserDisplay = computed(() => {
  if (selectedUserIndex.value >= 0 && patientUserList.value[selectedUserIndex.value]) {
    return patientUserList.value[selectedUserIndex.value].displayName
  }
  return ''
})

onMounted(async () => {
  await loadPatientUsers()
})

// 加载患者用户列表（只加载没有患者档案的用户）
async function loadPatientUsers() {
  try {
    uni.showLoading({ title: '加载患者列表...' })
    const userQueryObj = uniCloud.importObject('dh-user-query')
    // 🔥 使用新方法：只获取没有患者档案的患者用户
    const result = await userQueryObj.listPatientsWithoutProfile('with_role')
    
    console.log('listPatientsWithoutProfile 返回结果:', result)
    
    uni.hideLoading()
    
    if (result.code === 200 && result.data) {
      console.log('可用患者用户数据:', result.data)
      patientUserList.value = result.data.map(user => ({
        _id: user._id,
        displayName: user.displayName
      }))
      
      console.log('处理后的患者列表:', patientUserList.value)
      
      if (patientUserList.value.length === 0) {
        console.warn('未找到可用的患者用户')
        uni.showToast({ 
          title: '暂无可用的患者用户\n所有患者都已创建档案或请先创建患者账号', 
          icon: 'none', 
          duration: 3000 
        })
      } else {
        console.log(`成功加载 ${patientUserList.value.length} 个可用患者用户`)
      }
    } else {
      console.error('查询患者列表失败:', result)
      uni.showToast({ title: result.message || '加载患者列表失败', icon: 'none' })
    }
  } catch (error) {
    console.error('加载患者列表失败:', error)
    uni.hideLoading()
    uni.showToast({ title: '加载患者列表失败', icon: 'none' })
  }
}

// 用户选择改变
async function handleUserChange(e) {
  const index = parseInt(e.detail.value)
  selectedUserIndex.value = index
  if (index >= 0 && index < patientUserList.value.length) {
    const selectedUserId = patientUserList.value[index]._id
    formData.user_id = selectedUserId
    
    // 自动加载用户的实名认证信息
    await loadUserRealnameInfo(selectedUserId)
  }
}

// 从身份证号解析出生日期
function parseBirthDateFromIdCard(idCard) {
  if (!idCard || idCard.length < 14) return null
  
  // 身份证号第7-14位是出生日期（YYYYMMDD）
  const birthDateStr = idCard.substring(6, 14)
  if (birthDateStr.length !== 8) return null
  
  const year = parseInt(birthDateStr.substring(0, 4))
  const month = parseInt(birthDateStr.substring(4, 6))
  const day = parseInt(birthDateStr.substring(6, 8))
  
  // 验证日期有效性
  if (year < 1900 || year > new Date().getFullYear() || month < 1 || month > 12 || day < 1 || day > 31) {
    return null
  }
  
  const date = new Date(year, month - 1, day)
  return date.getTime()
}

// 加载用户实名认证信息
async function loadUserRealnameInfo(userId) {
  try {
    uni.showLoading({ title: '加载用户信息...' })
    
    const userQueryObj = uniCloud.importObject('dh-user-query')
    const result = await userQueryObj.getUser(userId, 'full')
    
    uni.hideLoading()
    
    if (result.code === 200 && result.data) {
      const userData = result.data
      console.log('用户完整信息:', userData)
      
      // 性别：从用户表的 gender 字段获取（0-未知，1-男，2-女）
      if (userData.gender !== undefined && userData.gender !== null) {
        formData.gender = userData.gender
        const genderOptIndex = genderOptions.findIndex(opt => opt.value === userData.gender)
        if (genderOptIndex !== -1) {
          genderIndex.value = genderOptIndex
        }
      }
      
      // 患者联系电话：从用户表的 mobile 字段获取
      if (userData.mobile) {
        formData.mobile = userData.mobile
      }
      
      // 手机号认证状态：从用户表的 mobile_confirmed 字段获取
      if (userData.mobile_confirmed !== undefined && userData.mobile_confirmed !== null) {
        formData.mobile_confirmed = userData.mobile_confirmed
      }
      
      // 从实名认证信息中提取数据
      if (userData.realname_auth) {
        const auth = userData.realname_auth
        
        // 身份证号：从 realname_auth.identity 获取
        if (auth.identity) {
          formData.id_card = auth.identity
          
          // 从身份证号解析出生日期
          const birthTimestamp = parseBirthDateFromIdCard(auth.identity)
          if (birthTimestamp) {
            formData.birth_date = birthTimestamp
            
            const date = new Date(birthTimestamp)
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            birthDateStr.value = `${year}-${month}-${day}`
          }
        }
      }
      
      console.log('自动填充后的表单数据:', formData)
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
    uni.hideLoading()
  }
}

function handleBloodTypeChange(e) {
  bloodTypeIndex.value = parseInt(e.detail.value)
  formData.blood_type = bloodTypeOptions[bloodTypeIndex.value]
}

function handleInputFocus(e) {
  // 输入框获得焦点时的处理（如果需要可以添加逻辑）
  // uni-app的input组件在获得焦点时会自动处理placeholder
}

function handleInputBlur(e) {
  // 输入框失去焦点时的处理
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/patients/list' })
}

async function handleSubmit() {
  // 验证必填项
  if (!formData.user_id || formData.gender === undefined || !formData.birth_date) {
    uni.showToast({ title: '请填写必填项', icon: 'none' })
    return
  }
  
  // 处理数组字段
  formData.allergies = allergiesStr.value ? allergiesStr.value.split(/[,，]/).map(s => s.trim()).filter(Boolean) : []
  formData.chronic_diseases = chronicDiseasesStr.value ? chronicDiseasesStr.value.split(/[,，]/).map(s => s.trim()).filter(Boolean) : []
  
  try {
    uni.showLoading({ title: '保存中...' })
    const dhPatients = uniCloud.importObject('dh-patients')
    const result = await dhPatients.createPatient(formData)
    uni.hideLoading()
    
    if (result.code === 201 || result.code === 200) {
      uni.showToast({ title: '创建成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/patients/list' })
      }, 1500)
    } else {
      uni.showToast({ title: result.message || '创建失败', icon: 'none' })
    }
  } catch (err) {
    console.error('创建失败:', err)
    uni.hideLoading()
    uni.showToast({ title: err.message || '创建失败', icon: 'none' })
  }
}
</script>

<style lang="scss" scoped>
.patient-add-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.page-header {
  background: #fff;
  padding: 30rpx 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 16rpx;
}

.btn {
  padding: 12rpx 24rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  white-space: nowrap;
  min-width: 100rpx;
  text-align: center;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}

.form-content {
  padding: 20rpx;
}

.form-card {
  background: #fff;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
  margin-bottom: 20rpx;
}

.card-header {
  background: #fafafa;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #e0e0e0;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.card-body {
  padding: 32rpx;
}

.form-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &.required .label::before {
    content: '*';
    color: #ff3b30;
    margin-right: 8rpx;
  }
}

.label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
  font-weight: 500;
}

.input {
  width: 100%;
  min-height: 80rpx;
  padding: 16rpx 24rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
  box-sizing: border-box;
  line-height: 48rpx;
  
  &:focus {
    border-color: #007aff;
    background: #f9fbff;
  }
  
  &::placeholder {
    color: #999;
    font-size: 26rpx;
  }
}

.picker-input {
  width: 100%;
  min-height: 80rpx;
  padding: 16rpx 24rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
  color: #333;
  box-sizing: border-box;
  line-height: 48rpx;
  display: flex;
  align-items: center;
}

.readonly-field {
  width: 100%;
  min-height: 80rpx;
  padding: 16rpx 24rpx;
  border: 1rpx solid #e8e8e8;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #f5f5f5;
  color: #666;
  box-sizing: border-box;
  line-height: 48rpx;
  display: flex;
  align-items: center;
}

.phone-with-badge {
  width: 100%;
  display: flex;
  align-items: center;
  gap: 12rpx;
  
  .readonly-field {
    flex: 1;
  }
}

.verify-badge {
  padding: 6rpx 16rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  font-weight: 500;
  white-space: nowrap;
  
  &.verified {
    background: #d1fae5;
    color: #065f46;
  }
  
  &.unverified {
    background: #fee2e2;
    color: #991b1b;
  }
}
</style>


